package com.ytzl.itripsearch.controller;

import com.ytzl.common.CodeResultEnums;
import com.ytzl.common.ResponseData;
import com.ytzl.common.ResponseDataUtils;
import com.ytzl.vo.HotCityHotekVo;
import com.ytzl.vo.SearchHotCityVo;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 热门酒店查询控制器
 */
@RestController
@RequestMapping("/api")
public class TestHotelListController {

    @Autowired
    private SolrClient solrClient;

    @PostMapping("/searchItripHotelListByHotCity")
    public ResponseData<SearchHotCityVo> searchItripHotelListByHotCity(SearchHotCityVo hotCityVo) throws SolrServerException, IOException {
        //检查参数是否存在
        /**
         * 成功：success=true | 失败 success=false
         * 错误码：
         * 20003：系统异常，获取失败
         * 20004：城市id不能为空
         */
        //根据城市ID查询酒店列表：基于solr查询->配置solr
        if (hotCityVo==null || (hotCityVo.getCityId()==null)){
            return ResponseDataUtils.buildError(CodeResultEnums.CITY_ID_IS_NULL);
        }
        //根据城市ID查询酒店列表：基于solr查询->配置solr
        List<HotCityHotekVo> HotCityHotekVo=this.solrQueryHotCityHotelList(hotCityVo.getCityId());
        return ResponseDataUtils.buildSuccess(HotCityHotekVo);
    }


    public List<HotCityHotekVo> solrQueryHotCityHotelList(Integer cityId) throws SolrServerException, IOException {
//        HotCityHotekVo hotCityHotekVo=new HotCityHotekVo();
//        ItripHotel itripHotel=new ItripHotel();
        List<HotCityHotekVo> HotCityHotekVoList=new ArrayList<>();
        //solr的查询条件构造对象
        SolrQuery query=new SolrQuery();
        //默认查所有
        query.setQuery("*:*");
        //设置其他查询条件
        query.setFilterQueries("cityId:"+cityId);

        QueryResponse response= solrClient.query(query);
        //获取查询结果
        SolrDocumentList results=response.getResults();
        //查询到的数量
        Long numFound=results.getNumFound();
        //遍历查询结果
        for (SolrDocument result : results) {
//            hotCityHotekVo.setCityId((Long)result.get(itripHotel.getCityid()));
//            hotCityHotekVo.setHotelName((String)result.get(itripHotel.getHotelname()));
            //将solr的查询结果转换为Java对象
            HotCityHotekVo hotCityHotekVo = solrClient.getBinder().getBean(HotCityHotekVo.class, result);
            HotCityHotekVoList.add(hotCityHotekVo);
        }
        return HotCityHotekVoList;
    }
}
